
/**
 * 首页数据状态Model
 * Create by Songlcy
 */
import 'package:scoped_model/scoped_model.dart';
import 'package:flutter_app_visitor/models/pood/Result_data_model.dart';
import 'dart:convert' as convert;

import './base_state_model.dart';
import '../../common/api.dart';
import '../../utils/http_util.dart';
import '../../common/status.dart';
import '../pood/Index_tab_model.dart';
import '../pood/index_tab_page_model.dart';

class HomeStateModel extends BaseStateModel {

  Status _status = Status.READY;
  Status get status => _status;

  List<IndexTabModel> _tabList = [];
  List<IndexTabModel> get tabList => _tabList;

  late PayLoad _payload;
  PayLoad get payload => _payload;

  late Map<int, List<Hot>> hotMap = Map<int, List<Hot>>();

  /**
   * 加载首页Tab分类列表
   */
  fetchTabList() async {
    _status = Status.LOADING;
    Map<String, dynamic> map = Map<String,dynamic>();

    await HttpUtil.get(INDEX_TAB_URL, map)
    .then((res) {
      _tabList = <IndexTabModel>[];
      if(res.statusCode == Response.OK) {
        _status = Status.SUCCESS;
        ResultDataModel resData = ResultDataModel.fromJson(convert.jsonDecode(res.data)) ;

        List<dynamic> responseList = resData.data as List<dynamic>;

        if(responseList.length > 0) {
          responseList.forEach((item) {
            IndexTabModel itdat =  IndexTabModel.fromJson(item);
            _tabList.add(itdat);
          });
        } else {
          _status = Status.NO_RESULT;
        }
        return _tabList;
      } else {
        _status = Status.NO_RESULT;
      }
    })
    .catchError((onError) {
      _tabList = [];
      print(onError.toString());
      _status = Status.ERROR;
    })
    .whenComplete(this.notifyListeners);
  }

  /**
   * 加载首页对应Tab分类
   */
  fetchIndexVideoList(int categoryId) {
    _status = Status.LOADING;
    Map<String, int> params = { "id": categoryId };

    HttpUtil.get(INDEX_VIDEO_LIST, params)
    .then((res) {
      if(res.statusCode == Response.OK) {
        _status = Status.SUCCESS;
        ResultDataModel resData = ResultDataModel.fromJson(convert.jsonDecode(res.data)) ;

        dynamic responseData = resData.data as dynamic;
        if(responseData != null) {
          _payload = PayLoad.fromJson(responseData);
          hotMap.addAll({ categoryId: _payload.hots });
        } else {
          _status = Status.NO_RESULT;
        }
      } else {
        _status = Status.NO_RESULT;
      }
    })
    .catchError((onError) {
      _status = Status.ERROR;
      print("====================>");
      print(onError.toString());
    })
    .whenComplete(this.notifyListeners);
  }

  static HomeStateModel of(context) => 
    ScopedModel.of<HomeStateModel>(context, rebuildOnChange: true);
}